package com.itheima.service;

import com.alibaba.dubbo.config.annotation.Service;
import com.itheima.dao.OrderSettingDao;
import com.itheima.pojo.OrderSetting;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service(interfaceClass = OrderSettingService.class)
@Transactional
public class OrderSettingServiceImpl implements OrderSettingService {

    @Autowired
    private OrderSettingDao orderSettingDao;

    @Override
    public void add(List<OrderSetting> list) {
        if (list != null && list.size() > 0) {
            for (OrderSetting orderSetting : list) {
                long count = orderSettingDao.findCountByOrderDate(orderSetting.getOrderDate());
                if (count > 0) {
                    orderSettingDao.editNumberByOrderDate(orderSetting);
                } else {
                    orderSettingDao.add(orderSetting);
                }
            }
        }
    }

    @Override
    public List<Map> getOrderSettingByMonth(String date) {//data:"2020-1"
        String startday = date + "-1";//"2020-1-1"
        String lastday = date + "-31";//"2020-1-31"
        //将查询条件封装成map
        Map<String, String> map = new HashMap<>();
        map.put("dateBegin", startday);
        map.put("dateEnd", lastday);
        List<OrderSetting> orderSettings = orderSettingDao.getOrderSettingByMonth(map);
        //创建list集合将得到的map封装
        List<Map> data = new ArrayList<>();
        for (OrderSetting orderSetting : orderSettings) {
            //创建map集合将每一行的数据存入
            Map orderSettingMap = new HashMap();
            orderSettingMap.put("date", orderSetting.getOrderDate().getDate());//获得日期几号
            orderSettingMap.put("number", orderSetting.getNumber());//可预约人数
            orderSettingMap.put("reservations", orderSetting.getReservations());//已预约人数
            data.add(orderSettingMap);
        }
        return data;
    }

    @Override
    public void editNumberByDate(OrderSetting orderSetting) {
        long orderDate = orderSettingDao.findCountByOrderDate(orderSetting.getOrderDate());
        //判断是否存在
        if (orderDate > 0) {
            //已经存在，进行修改操作
            orderSettingDao.editNumberByOrderDate(orderSetting);
        } else {
            //不存在，进行添加操作
            orderSettingDao.add(orderSetting);
        }
    }
}
